package models

import (
	"chat/utils"
	"fmt"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Name     string `valid:"required"`               // 非空验证
	Password string `valid:"required,length(6|100)"` // 非空且最小长度6
	Phone    string `valid:"matches(^1[3-9]{1}\\d{9}$)"`
	Email    string `valid:"email"`
}

func (table *User) TableName() string {
	return "user"
}

func GetUserList() []*User {
	data := make([]*User, 10)
	utils.DB.Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}
	return data
}

type UserVo struct {
	Id       uint   `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
	Phone    string `json:"phone"`
	Email    string `json:"email"`
}

func UserListToVO(userList []*User) []*UserVo {
	userVoList := make([]*UserVo, len(userList))
	for i, v := range userList {
		userVoList[i] = &UserVo{
			Id:       v.ID,
			Name:     v.Name,
			Password: v.Password,
			Phone:    v.Phone,
			Email:    v.Email,
		}
	}
	return userVoList
}

func CreateUser(user User) uint {
	utils.DB.Create(&user)
	return user.ID
}

func DelUser(id string) {
	utils.DB.Delete(&User{}, id)
}

func UpdateUser(user User) {
	utils.DB.Model(&user).Updates(User{
		Name:     user.Name,
		Email:    user.Email,
		Phone:    user.Phone,
		Password: user.Password,
	})
	return
}

func FindUserByName(name string) User {
	user := User{}
	utils.DB.Where("name = ?", name).First(&user)
	return user
}

func FindUserByPhone(phone string) User {
	user := User{}
	utils.DB.Where("phone = ?", phone).First(&user)
	return user
}

func FindUserByEmail(email string) User {
	user := User{}
	utils.DB.Where("email = ?", email).First(&user)
	return user
}

func FindUserByNameAndPassword(name string) User {
	user := User{}
	utils.DB.Where("name = ?", name).First(&user)
	return user
}
